#include "Pipe.h"

Pipe :: Pipe() {
	pipe ( this->descriptors );
	fcntl ( this->descriptors[0],F_SETFL,O_NONBLOCK );
	fcntl ( this->descriptors[1],F_SETFL,O_NONBLOCK );
	this->reading = true;
	this->writing = true;
}

void Pipe :: setMode ( int mode ) {
	if ( mode == READING ) {
		close ( this->descriptors[1] );
		this->writing = false;

	} else if ( mode == WRITING ) {
		close ( this->descriptors[0] );
		this->reading = false;
	}
}

int Pipe :: writeToPipe ( char* data,int dataSize ) {
	if ( this->reading == true ) {
		close ( this->descriptors[0] );
		this->reading = false;
	}

	int result = write ( this->descriptors[1],data,dataSize );
	return result;
}

int Pipe :: readFromPipe ( char* buffer,int buffSize ) {
	if ( this->writing == true ) {
		close ( this->descriptors[1] );
		this->writing = false;
	}

	int result = read ( this->descriptors[0],buffer,buffSize );
	return result;
}

int Pipe :: getReadingFD () {
	if ( this->reading == true )
		return this->descriptors[0];
	else
		return -1;
}

int Pipe :: getWritingFD () {
	if ( this->writing == true )
		return this->descriptors[1];
	else
		return -1;
}

void Pipe :: closePipe () {
	if ( this->reading == true ) {
		close ( this->descriptors[0] );
		this->reading = false;
	}

	if ( this->writing == true ) {
		close ( this->descriptors[1] );
		this->writing = false;
	}
}

Pipe::~Pipe() {
}
